from loguru import logger
import commons
from configs import Configs


class DataHelper:
    def __init__(self, interval=None):  # 添加interval参数方便查其他k线数据
        if interval is None:
            interval = Configs().get_configs()["程序k线"]
        self.interval = interval

    def get_k_lines(self):
        return commons.get_client_anonymous().get_klines(symbol=Configs().get_configs()["交易对"],
                                                         interval=self.interval, limit=1000)

    def get_ema(self, n: int, k_lines=None):
        if k_lines is None:
            k_lines = self.get_k_lines()
        current_ema = 0
        ema_n_list = list()
        alpha = 2.0 / (n + 1)
        beta = 1 - alpha
        for k_line in k_lines:
            close = float(k_line[4])
            current_ema = alpha * close + beta * current_ema
            ema_n_list.append(current_ema)

        return [round(x, 2) for x in ema_n_list[-3:]]


def test():
    configs = Configs()
    configs.get_configs_from_db()
    data_helper = DataHelper()
    k_lines = data_helper.get_k_lines()
    logger.debug(len(k_lines))
    ema = data_helper.get_ema(3, k_lines)
    logger.debug(ema[-5:])
    ema = data_helper.get_ema(55, k_lines)
    logger.debug(ema[-5:])
    ema = data_helper.get_ema(233, k_lines)
    logger.debug(ema[-5:])


if __name__ == '__main__':
    test()
